import { useState, useEffect, useCallback, useRef } from "react";

/**
 * 监听元素是否可见
 *
 * @param {Object} options IntersectionObserver 参数
 * @param {Boolean} triggerOnce 是否只触发一次
 * @returns {[Ref, Boolean]} targetRef, isIntersecting
 */
const useObserver = (
  options = {
    root: null,
    rootMargin: "0px 0px",
    threshold: 1,
  },
  triggerOnce = true
) => {
  const [isIntersecting, setIsIntersecting] = useState(false);
  const targetRef = useRef(null);

  const handle = useCallback(() => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          setIsIntersecting(true);
          triggerOnce && observer.unobserve(entry.target);
        } else {
          setIsIntersecting(false);
        }
      });
    }, options);

    targetRef.current && observer.observe(targetRef.current);

    return () => targetRef.current && observer.unobserve(targetRef.current);
  }, [options, triggerOnce]);

  useEffect(() => handle(), [handle]);

  return [targetRef, isIntersecting];
};

export default useObserver;
